package com.roc.web.action.terminal;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TPosInfo;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.YjPosInfo;
import com.roc.service.IExcelExportService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.DateUtil;
import com.roc.util.Utils;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.util.constant.Terminal;


/**
 * 云商宝终端查询action
 * @ClassName YsbTermSnQueryAction
 * @author JD
 * @date 2018年1月10日
 *
 */
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/ysbTermSn")
public class YsbTermSnQueryAction extends PaginationBaseAction {

	private static final long serialVersionUID = 1L;

	static Logger logger = LogManager.getLogger(YsbTermSnQueryAction.class);

	private YsbTermSnQuerySearchCondition searchCondition;

	private List<TblInsInf> orgList = new ArrayList<TblInsInf>();

	private InputStream excelFile;
	
	private String excelName;

	@Autowired
	IPageService pagenitionService;

	@Autowired
	private IorgService orgService;

	@Autowired
	private IExcelExportService iexcelSerivce;
	
	
	
	@Autowired
	IPowerInfoService powerInfoService;
	/**
	 * 商服宝终端sn查询主页
	 * @Title: termQrtInit
	 * @return
	 * @throws Exception
	 * @author JD
	 * @date: 2018年1月10日 
	 *
	 */
	@Action(value = "init", results = { @Result(location = "/pages/terminal/YsbTermSnQuery.jsp") })
	public String termQrtInit() throws Exception {
		org();
		return SUCCESS;
	}
    /**
     *  商服宝终端sn查询
     * @Title: queryTerminalPosSNAction
     * @return
     * @throws Exception
     * @author JD
     * @date: 2018年1月10日 
     *
     */
	@Action(value = "queryTermSn", results = { @Result(name = "success", location = "/pages/terminal/YsbTermSnQuery.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	// 查询终端
	public String queryTermSn() throws Exception {

		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if (searchCondition == null) {
			searchCondition = (YsbTermSnQuerySearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new YsbTermSnQuerySearchCondition();
			}
		}
		try {
			org();
			if(op.getRoleType().equals(Role.MARKET_DIRECT.getCode()) ||op.getRoleType().equals(Role.MARKET_LEAD.getCode())){
				addActionError("销售无权限查询");
				return ERROR;
			}
			// 如果当前登录账号是仓库管理员
			if(op.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode())){
		        searchCondition.setOpId(String.valueOf(op.getId()));//当前人员id
		        searchCondition.setRoleType(op.getRoleType());// 角色
		        searchCondition.setOperators(op.getAccountNo());//当前登陆账号
			} else {
				Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
		        String superRole= map.get("superRole");
		        String opRealId =map.get("opRealId");
		        searchCondition.setRoleType(superRole);// 角色
		        searchCondition.setOpId(opRealId);//当前人员id
		        searchCondition.setOneOrgCode(op.getOneagentid());//机构
			}
				int rows = pagenitionService.countSQL(searchCondition);
	
				searchRsList = pagenitionService.findAllSQL(searchCondition,calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
	
				List<TPosInfo> posList = new ArrayList<TPosInfo>();
				if (searchRsList != null && searchRsList.size() > 0) {
					Iterator iterator = searchRsList.iterator();
					while (iterator.hasNext()) {
						Object[] obj = (Object[]) iterator.next();
						TPosInfo pos = new TPosInfo();
						pos.setSerialNum(Constance.Null2EmptyTrim(obj[0]));
	
						String brandCode = obj[1] + "";
						String typeCode = obj[2] + "";
						String nameCode = obj[3] + "";
						
						pos.setPosBrand(ConfigMerinfoUtil.getPosBRAND(brandCode));
						pos.setPosName(ConfigMerinfoUtil.getPosMODEL(nameCode , brandCode));
						pos.setPosType(ConfigMerinfoUtil.getTerminalType(typeCode));
						
						pos.setOrgCode(Constance.Null2EmptyTrim(obj[4]));
						pos.setIsBind(Terminal.valueOfCode(Constance.Null2EmptyTrim(obj[5])).getName());
						pos.setIsUsed(Terminal.valueOfCode(Constance.Null2EmptyTrim(obj[6])).getName());
						pos.setMercCode(Constance.Null2EmptyTrim(obj[7]));
						pos.setTermCode(Constance.Null2EmptyTrim(obj[8]));
						pos.setRemark(Constance.Null2EmptyTrim(obj[9]));
						pos.setInDateStr(DateUtil.formatTime(Constance.Null2EmptyTrim(obj[10])));
						pos.setOutDateStr(DateUtil.formatTime(Constance.Null2EmptyTrim(obj[11])));
						pos.setAgentName(Constance.Null2EmptyTrim(obj[12]));
						if ( !"".equals( Constance.Null2EmptyTrim(obj[13]) ) ){
							pos.setTekId(Terminal.valueOfCode(Constance.Null2EmptyTrim(obj[13])).getName());
						}
						String snCls = "";
						String bCls = Constance.Null2EmptyTrim(obj[14]);
						if ( !"".equals( bCls ) ){
							snCls = Utils.getYsbSnClassMap().get(bCls);
						}
						pos.setSnClass(snCls);

						pos.setActDateStr(Constance.Null2EmptyTrim(obj[15]));
						pos.setMchtName(Constance.Null2EmptyTrim(obj[16]));
						pos.setPhone(Constance.Null2EmptyTrim(obj[17]));
						pos.setMchtCrtDateStr(Constance.Null2EmptyTrim(obj[18]));
						
						posList.add(pos);
					}
				}
			searchRsList.clear();
			searchRsList.addAll(posList);
			dealWithTheListSpecially(searchRsList);
			this.setTotalPage(this.calcuTotalPage(rows));
			addActionMessage("当前条件下统计到【"+rows+"】条记录");		
			getRequest().setAttribute("posList", posList);			
			getRequest().setAttribute("agenid", searchCondition.getAgentId());
			getRequest().setAttribute("selModelCode", searchCondition.getPosName());
			getRequest().setAttribute("oldBandCode", searchCondition.getPosBrand());			
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}

		return SUCCESS;
	}

	private void org() {
		try {
			Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			TblInsInf infs=orgService.queryOrgByOrgCode(logingMerchant.getOrgCode());
			orgList.add(infs);
			getRequest().setAttribute("brandMap",ConfigProperties.getYsbBrandProperties());
			getRequest().setAttribute("nameMap", new ArrayList<Map<String,Object>>());
			getRequest().setAttribute("typeMap", ConfigProperties.getSysDB1("Terminal_Type",true));
			
			getRequest().setAttribute("netInTypeMap", Utils.getNetInTypeMap());
			getRequest().setAttribute("use288Map", Utils.getUse288Map());
			getRequest().setAttribute("ysbIsDirectlyMap", Utils.getYsbIsDirectlyMap());
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		ActionContext.getContext().put("merchantList", null);
	}

	protected void dealWithTheListSpecially(List<Object> list) {
		super.dealWithTheListSpecially(list);
		Map<String, String> roleTypes = ConfigProperties.getRoleTypeProperties();
		List<Object> tempList = new ArrayList<Object>();
		for (Object obj : list) {
			TPosInfo pos = (TPosInfo) obj;
			for (TblInsInf bean : orgList) {
				if (pos.getOrgCode().equals(bean.getInsIdCd())) {
					pos.setOrgName(bean.getInsName());
				}
			}

			//		手机用*代替
			if ( !"".equals( Constance.Null2EmptyTrim(pos.getPhone()) ) ){
				pos.setPhone(Utils.dealMobile(Constance.Null2EmptyTrim(pos.getPhone())));
			}
			tempList.add(pos);
		}
		searchRsList = tempList;
	}

	/**
	 * * 商服宝终端sn导出
	 * @Title: settingExcelqQuery
	 * @return
	 * @throws Exception
	 * @author JD
	 * @date: 2018年1月10日 
	 *
	 */
	@Action(value = "excelTermSn", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/error.jsp") })
	public String excelTermSn() throws Exception {

		ByteArrayOutputStream output = new ByteArrayOutputStream();
		String[] headArray = { "终端序列号", "商户号", "商户名称", "手机号", "注册时间", "终端号", "所属代理商", "品牌", "型号",/*"机型",*/
				"是否已绑定", "是否已出库", /*"备注", */"入库时间", "出库时间", "是否有效", "激活时间","等级" };
		String reportName = "云商宝终端SN导出";
		try {
			Operators op = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
			if (searchCondition == null) {
				searchCondition = (YsbTermSnQuerySearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new YsbTermSnQuerySearchCondition();
				}
			}
			org();
			if(op.getRoleType().equals(Role.MARKET_DIRECT.getCode()) ||op.getRoleType().equals(Role.MARKET_LEAD.getCode())){
				addActionError("销售无权限下载");
				return ERROR;
			}
			// 如果当前登录账号是仓库管理员
			if(op.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode())){
		        searchCondition.setRoleType(op.getRoleType());// 角色
		        searchCondition.setOperators(op.getAccountNo());//当前登陆账号
		        searchCondition.setOpId(String.valueOf(op.getId()));//当前人员id
			} else {
				Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
		        String superRole= map.get("superRole");
		        String opRealId =map.get("opRealId");
		        searchCondition.setRoleType(superRole);// 角色
		        searchCondition.setOpId(opRealId);//当前人员id
		        searchCondition.setOneOrgCode(op.getOneagentid());//机构
			}
			int rows = pagenitionService.countSQL(searchCondition);

			searchRsList = pagenitionService.findAllSQL(searchCondition, 0,rows);

			searchRsList = dealData(searchRsList, headArray.length);

			if ( null == searchRsList || searchRsList.size() <= 0 ){
				searchRsList = new ArrayList<Object>();
			}
			
			setExcelName(new String(reportName.getBytes(), "ISO8859-1"));

			HSSFWorkbook work = iexcelSerivce.excelExport(reportName,headArray, searchRsList);
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);

		} catch (Exception e) {
			logger.info("######导出" + reportName + "失败######");
			addActionError(e.getMessage());
			return ERROR;
		} finally {
			closeOutPut(output);
		}

		return SUCCESS;
	}

	private List<Object> dealData(List<Object> searchRsList, int size)
			throws ServiceException {
		List<Object> searchRsListNew = new ArrayList<Object>();

		if (searchRsList == null || searchRsList.size() == 0) {
			return null;
		}
		Iterator iterator = searchRsList.iterator();
		while (iterator.hasNext()) {
			Object[] obj = (Object[]) iterator.next();
			Object[] objNew = new Object[size];

			objNew[0] = Constance.Null2EmptyTrim(obj[0]);
			objNew[1] = Constance.Null2EmptyTrim(obj[7]);
			objNew[2] = Constance.Null2EmptyTrim(obj[16]);

			objNew[3] = "";
			//		手机用*代替
			if ( !"".equals( Constance.Null2EmptyTrim(obj[17]) ) ){
				objNew[3] = Utils.dealMobile(Constance.Null2EmptyTrim(obj[17])) ;
			}
			objNew[4] = Constance.Null2EmptyTrim(obj[18]);
			objNew[5] = Constance.Null2EmptyTrim(obj[8]);
			objNew[6] = Constance.Null2EmptyTrim(obj[12]);

			String brandCode = obj[1] + "";
//			String typeCode = obj[2] + "";
			String nameCode = obj[3] + "";
			
			objNew[7] = ConfigMerinfoUtil.getPosBRAND(brandCode);
			objNew[8] = ConfigMerinfoUtil.getPosMODEL(nameCode , brandCode);
		//	objNew[6] = ConfigMerinfoUtil.getTerminalType(typeCode);
			
			objNew[9] = Terminal.valueOfCode(Constance.Null2EmptyTrim(obj[5])).getName();
			objNew[10] = Terminal.valueOfCode(Constance.Null2EmptyTrim(obj[6])).getName();
		//	objNew[9] = Constance.Null2EmptyTrim(obj[9]);
			objNew[11] = DateUtil.formatTime(Constance.Null2EmptyTrim(obj[10]));
			objNew[12] = DateUtil.formatTime(Constance.Null2EmptyTrim(obj[11]));

			objNew[13] = "";
			if ( !"".equals( Constance.Null2EmptyTrim(obj[13]) ) ){
				objNew[13] = Terminal.valueOfCode(Constance.Null2EmptyTrim(obj[13])).getName();
			}
			objNew[14] = Constance.Null2EmptyTrim(obj[15]);
			String snCls = "";
			String bCls = Constance.Null2EmptyTrim(obj[14]);
			if ( !"".equals( bCls ) ){
				snCls = Utils.getYsbSnClassMap().get(bCls);
			}
			objNew[15] = snCls;
			searchRsListNew.add(objNew);
		}

		return searchRsListNew;

	}

	private void closeOutPut(ByteArrayOutputStream output)
			throws ServiceException {

		try {
			if (output != null) {
				output.flush();
				output.close();
			}
		} catch (IOException e) {
			logger.error("########导出Excel关闭流失败######", e);
			throw new ServiceException("导出Excel关闭流失败！");
		}
	}

	private String getOrgName(String key) {

		if (orgList == null || "".equals(key)) {
			return "";
		}
		for (TblInsInf bean : orgList) {
			if (key.equals(bean.getInsIdCd()))
				return bean.getInsName();
		}

		return "";

	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (YsbTermSnQuerySearchCondition) getSession().getAttribute(
				SEARCH_SESSION_BEAN_YSBTERM_SN_QUERY);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_YSBTERM_SN_QUERY,
				searchCondition);
	}

	

	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	

	public YsbTermSnQuerySearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(YsbTermSnQuerySearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		return excelName;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}

}
